<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-10
 * Time: 16:00
 * 用户订单实际操作
 */

namespace app\api\service\member;


use app\api\model\MemberCost;
use app\api\model\MemberOrder;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class MemberOrderSer extends Token
{
    // 会员费ID
    private $costId;

    // 会员费
    private $costInfo;

    // 用户
    private $user;

    function __construct($costId)
    {
        $this->costId = $costId;
    }

    // 创建会员支付订单入口
    public function place()
    {
        return $this->getInfo();
    }

    // 获取会员费详情
    private function getInfo()
    {
        $this->costInfo = MemberCost::get($this->costId);
        if(!$this->costInfo) {
            throw new ParameterException([
                'msg' => [
                    'member' => '请重新选择会员费'
                ]
            ]);
        }
        return $this->getUserInfo();
    }

    // 获取用户信息
    private function getUserInfo()
    {
        $uid = self::getCurrentUid();
        $this->user = User::where('id',$uid)->with('member')->find();
        if(!$this->user['member']) {
            throw new ParameterException([
                'msg' => [
                    'member' => '请先添加会员信息'
                ]
            ]);
        }
        return $this->createOrder();
    }

    // 创建订单
    private function createOrder()
    {
        // 删除未支付的订单
        MemberOrder::destroy([ 'user_id'=>$this->user['id'], 'status'=>1 ]);
        // 创建订单
        Db::startTrans();
        try{
            $mode = MemberOrder::create([
                'member_id' => $this->user['member']['id'],
                'user_id' => $this->user['id'],
                'member_cost_id' => $this->costId,
                'price' => $this->costInfo['price'],
                'order_no' => self::makeOrderNo()
            ]);
            $out_trade_no = '1you2020'.$mode->id;
            MemberOrder::where('id',$mode->id)->update([
                'out_trade_no' => $out_trade_no
            ]);
            Db::commit();
            return writeJson(201, [ 'out_trade_no'=>$out_trade_no ], '订单生成成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}